package com.shark.shiro;

import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.shark.commons.spring.SpringContextHolder;
import com.shark.manager.system.entity.User;
import com.shark.manager.system.service.UserService;

public class ShiroAuthRealm extends AuthorizingRealm {

	private static final Logger logger = LoggerFactory
			.getLogger(ShiroAuthRealm.class);

	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		logger.info("授权....");
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		return authorizationInfo;
	}

	/**
	 * 登录验证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
		String account = usernamePasswordToken.getUsername();
		// String password = new String((char[])
		// usernamePasswordToken.getPassword());

		UserService userService = SpringContextHolder.getBean(UserService.class);
		User user = userService.findByAccount(account);

		if (user == null) {
			throw new UnknownAccountException(); // 没找到帐号
		} else if (null != user.getLocked() && user.getLocked() == -1) { // 账号被锁定
			throw new DisabledAccountException();
		}

		return new SimpleAuthenticationInfo(account, user.getPassword(),
				ByteSource.Util.bytes(user.getCredentialsSalt()), getName());
	}

	/**
	 * 用户退出登录执行清除认证缓存方法 认证缓存，保存的是用户名
	 */
	@Override
	public void clearCachedAuthenticationInfo(PrincipalCollection principals) {
		logger.info("---------------------清除认证缓存---------------------");

		Cache<Object, AuthenticationInfo> c = this.getAuthenticationCache();
		Set<Object> keys = c.keys();
		for (Object o : keys) {
			logger.info("key：" + o + " ------- value：" + c.get(o));
		}
		SimplePrincipalCollection spc = new SimplePrincipalCollection(
				principals.getPrimaryPrincipal(), getName());
		super.clearCachedAuthenticationInfo(spc);
	}

	/**
	 * 用户退出登录执行清除授权缓存方法 授权缓存，保存的是用户对象，直接清除即可
	 */
	@Override
	public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
		logger.info(" ---------------------清除授权缓存---------------------");
		Cache<Object, AuthorizationInfo> c = this.getAuthorizationCache();

		Set<Object> keys = c.keys();
		for (Object o : keys) {
			logger.info(" key：" + o + " ------- value：" + c.get(o));
		}

		super.clearCachedAuthorizationInfo(principals);
	}

	@Override
	public void clearCache(PrincipalCollection principals) {
		System.out.println("====clearCache======");
		super.clearCache(principals);
	}
}
